<template>
  <!-- 1. 应用于列表滚动，获取wrapper的DOM -->
  <div class="list" ref="wrapper">
    <div>
      <div class="area">
        <div class="title border-topbottom">当前城市</div>
        <div class="button-list">
          <div class="button-wrapper">
            <div class="button">{{this.currentCity}}</div>
          </div>
        </div>
      </div>
      <div class="area">
        <div class="title border-topbottom">热门城市</div>
        <div class="button-list">
          <!-- 1. Vuex的使用，绑定方法 -->
          <div class="button-wrapper"
            v-for="item of hot"
            :key="item.id"
            @click="handleCityClick(item.name)"
          >
            <div class="button">{{item.name}}</div>
          </div>
        </div>
      </div>
      <!-- 对象循环，第二项为 key 值 -->
      <div class="area" v-for="(item, key) of cities" :key="key" :ref="key">
        <div class="title border-topbottom">{{key}}</div>
        <div class="item-list">
          <!-- 二次循环 -->
          <div class="item border-bottom"
            v-for="innerItem of item"
            :key="innerItem.id"
            @click="handleCityClick(innerItem.name)"
          >
            {{innerItem.name}}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'CityList',
  props: {
    cities: Object,
    hot: Array,
    letter: String
  },
  computed: {
    ...mapState({
      currentCity: 'city'
    })
  },
  // 2. Vuex的使用，使用方法
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  // 监听父组件传递的 letter的变化
  watch: {
    letter () {
      if (this.letter) {
        const element = this.$refs[this.letter][0]
        this.scroll.scrollToElement(element)
      }
    }
  },
  // 2. 应用于列表滚动，写生命周期函数，会在页面DOM挂载完毕后执行
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper)
  }
}
</script>

<style lang="stylus" scoped>
  // 控制1px边框的颜色
  .border-topbottom
    &:before
      border-color #ccc
    &:after
      border-color #ccc
    .border-bottom
      &:before
        border-color #ccc
  .list
    overflow hidden
    position absolute
    top 81px
    left 0
    right 0
    bottom 0
    .title
      line-height 25px
      background-color #eee
      padding-left 10px
      color #666666
      font-size 13px
    .button-list
      overflow hidden
      padding 2px 30px 2px 2px
      .button-wrapper
        float left
        width 33.33%
        .button
          margin 5px
          padding 3px 0
          text-align center
          border 1px solid #ccc
          border-radius 3px
          color #101010
    .item-list
      .item
        line-height 36px
        color #101010
        padding-left 10px
</style>
